################################################################################
##
## Purpose: This script creates Figure 3, along with SI figure 8 and SI table 3.
##
## Author: James Bisbee (james.h.bisbee@vanderbilt.edu)
##
## Input Files:
##  - ./data/prepped/finalData.RData: Prepped data from 9_DATA_final_build.R
##
## Output Files:
##  - ./output/figures/MS_figure_3.pdf
##  - ./output/tables/SI_table_3.tex
##  - ./output/figures/SI_figure_8.pdf
##
##
## See associated log file for compute environment, package versions, 
##  and date of most recent run.
##
################################################################################
rm(list = ls())
gc()
require(tidyverse)
require(ggridges)
require(fixest)

set.seed(123)

# Compute details
print(paste0('Compute environment from ',Sys.Date(),' run by Bisbee'))
if(Sys.info()['sysname'] == 'Windows') {
  ram_size = system("wmic MemoryChip get Capacity", intern = TRUE)[-1]
  model_name = system("wmic cpu get name", intern = TRUE)[2] # nocov
  vendor_id = system("wmic cpu get manufacturer", intern = TRUE)[2] # nocov
  
  print(list(ram = stringr::str_squish(ram_size)[1],
             vendor_id = stringr::str_squish(vendor_id),
             model_name = stringr::str_squish(model_name),
             no_of_cores = parallel::detectCores()))
} else if(Sys.info()['sysname'] == 'Linuxs') {
  splitted <- strsplit(system("ps -C rsession -o %cpu,%mem,pid,cmd", intern = TRUE), " ")
  df <- do.call(rbind, lapply(splitted[-1], 
                              function(x) data.frame(
                                cpu = as.numeric(x[2]),
                                mem = as.numeric(x[4]),
                                pid = as.numeric(x[5]),
                                cmd = paste(x[-c(1:5)], collapse = " "))))
  df
} else {
  cat("If not on Linux or Windows, you'll have to figure out your own solution to seeing the compute environment.")
}

sessionInfo()


load('./data/prepped/finalData.RData')

dims <- colnames(utterance_level %>% select(matches('SENT_'),-matches('_lag|error')) %>% select(-matches('SEVERE|AUTHOR|LIKELY')))

# Speaker intercepts, controlling for document, with minimum utterances > 100
mod1 <- feols(as.formula(paste0('interrupted ~ factor(opensecretsID)',
                                ' + poly(scale(log(nchars)),3) + interruptor +', # U-level covariates
                                paste(paste0('topic_',1:100),collapse = ' + '),
                                ' + ',
                                paste(paste0('scale(',dims[-which(grepl('comb',dims))],'_lag)'),collapse = ' + '),
                                ' + poly(scale(log(tot_utterances_lag)),3) + scale(votepct_lag) + gender_lag + scale(seniority_lag)', # X-level covariates
                                ' + scale(age_lag) + scale(nominate_dim1_lag) + constrain_empower_tot_lag + yellen_vote_lag',
                                '| docID')),
              utterance_level %>% 
                filter(all >= 100 & !grepl('EXPERT',opensecretsID) & ind > mind) %>%
                mutate(opensecretsID = paste0(opensecretsID,position)),
              cluster = 'interruptedBy')

toplot <- mod1$coeftable %>%
  data.frame() %>%
  rename_all(function(x) gsub('Estimate','est',gsub('Std..Error','se',gsub('t.value','tstat',gsub('Pr...t..','pval',x))))) %>%
  mutate(covs =rownames(.)) %>%
  filter(grepl('opensecrets',covs),
         !is.na(est)) %>%
  mutate(covs =  gsub('factor\\(opensecretsID\\)','',covs)) %>%
  as_tibble() %>%
  left_join(utterance_level %>% select(opensecretsID,position,party,gender,stab,speaker,name,all) %>% distinct() %>%
              mutate(opensecretsID = paste0(opensecretsID,position)),
            by = c('covs' = 'opensecretsID')) %>%
  mutate(stab = ifelse(grepl('Chairperson',covs),'DC',stab),
         id = gsub(' Chair','',gsub('Legislator','MC',gsub('Committee','Comm',gsub('Fed Chair: ','',paste0(str_to_title(name),' [',position,': ',party,'-',stab,' (',gender,')]'))))),
         fedID = ifelse(grepl('FED',covs),'Fed Chair','Not'))

cols <- ifelse(toplot$position[order(toplot$est)] == 'Committee Chair','blue',
               ifelse(toplot$position[order(toplot$est)] == 'Fed Chair','red','grey40'))

pdf('./output/figures/MS_figure_3.pdf',width = 7,height = 7)
toplot %>%
  ggplot(aes(x = est,y = reorder(id,est),color = position,shape = position)) + 
  geom_vline(xintercept = 0,linetype = 'dashed') + 
  geom_errorbarh(aes(xmin = est-2*se,xmax = est+2*se),height = 0,linewidth = .1) + 
  geom_point(aes(size = all),fill = 'white') + 
  theme_ridges() + 
  scale_color_manual(name = '',values = c('grey50','black','grey40')) +
  scale_shape_manual(name = '',values = c(15,19,21)) + 
  scale_size_continuous(name = 'Total Utterances',breaks = c(100,500,1000),range = c(2,7)) + 
  scale_y_discrete(expand = c(.05,0)) + 
  geom_text(data = toplot %>%
              filter(position == 'Fed Chair',
                     est < 0),show.legend  = FALSE,
            aes(x = est+2*se,y = reorder(id,est),label = gsub('\\[Fed-DC |\\]','',id)),size = 5,hjust = 0) + 
  geom_text(data = toplot %>%
              filter(position == 'Fed Chair',
                     est > 0),show.legend  = FALSE,
            aes(x = est-2*se,y = reorder(id,est),label = gsub('\\[Fed-DC |\\]','',id)),size = 5,hjust = 1.1,vjust = .5) + 
  geom_text(data = toplot %>%
              filter(position == 'Legislator'),show.legend  = FALSE,
            aes(x = est,y = reorder(id,est),label = gsub('.*\\(|\\).*','',id)),size = 2.5,hjust = .5,vjust = .5) + 
  geom_text(data = toplot %>%
              filter(position == 'Committee Chair'),show.legend  = FALSE,
            aes(x = est,y = reorder(id,est),label = gsub('.*\\(|\\).*','',id)),size = 2.5,hjust = .5,vjust = .5,color = 'white') + 
  xlab('Fixed Effect Intercept (Reference = Bernanke)') + 
  theme(legend.position = 'right',legend.box="vertical",panel.grid.major.y = element_blank(),
        axis.text.y = element_blank()) + 
  ylab('')
dev.off()


etable(mod1,
       extralines = list('100 LDA Topic Loadings' = c('Yes','Yes')),replace = T,
       drop = 'opensecretsID\\)N|topic',file = './output/tables/SI_table_3.tex')


# for appendix
mod <- feols(as.formula(paste0('interrupted ~ factor(opensecretsID)',
                                ' + poly(scale(log(nchars)),3) + interruptor +', # U-level covariates
                                paste(paste0('topic_',1:100),collapse = ' + '),
                                ' + ',
                                paste(paste0('scale(',dims[-which(grepl('comb',dims))],'_lag)'),collapse = ' + '),
                                ' + poly(scale(log(tot_utterances_lag)),3) + scale(votepct_lag) + gender_lag + scale(seniority_lag)', # X-level covariates
                                ' + scale(age_lag) + scale(nominate_dim1_lag) + constrain_empower_tot_lag + yellen_vote_lag',
                                '| docID')),
              utterance_level %>% filter(all > 30 & !grepl('EXPERT',opensecretsID) & ind > mind),
              cluster = 'interruptedBy')

toplot <- mod$coeftable %>%
  data.frame() %>%
  rename_all(function(x) gsub('Estimate','est',gsub('Std..Error','se',gsub('t.value','tstat',gsub('Pr...t..','pval',x))))) %>%
  mutate(covs =rownames(.)) %>%
  filter(grepl('opensecrets',covs),
         !is.na(est)) %>%
  mutate(covs =  gsub('factor\\(opensecretsID\\)','',covs)) %>%
  as_tibble() %>%
  left_join(utterance_level %>% select(opensecretsID,position,party,gender,stab,speaker,name,all) %>% distinct(),
            by = c('covs' = 'opensecretsID')) %>%
  mutate(party = ifelse(grepl('Expert',covs),'Expert',
                        ifelse(grepl('Chairperson',covs),'FED',party)),
         stab = ifelse(grepl('Chairperson',covs),'DC',stab),
         id = paste0(str_to_title(name),' [',party,'-',stab,' (',gender,')]'),
         fedID = ifelse(grepl('FED',covs),'Fed Chair','Not'))

pdf('./output/figures/SI_figure_8.pdf',width = 9,height = 11)
toplot %>%
  ggplot(aes(x = est,y = reorder(id,est),color = fedID,label = all)) + 
  geom_vline(xintercept = 0,linetype = 'dashed') + 
  geom_errorbarh(aes(xmin = est-2*se,xmax = est+2*se),height = 0) + 
  geom_point(aes(size = all),shape = 21,fill = 'white') + 
  theme_ridges() + 
  scale_color_manual(name = '',values = c('red','grey40'),breaks = c('Fed Chair'),labels = c('Fed Chair')) + 
  scale_size_continuous(name = 'Total Utterances',breaks = c(20,100,500,1000),range = c(2,7)) + 
  xlab('Fixed Effect Intercept (Reference = Bernanke)') + 
  theme(legend.position = 'bottom',legend.box="vertical") + 
  geom_text(nudge_x = .05,hjust = 0,size = 2.5) + 
  theme(axis.text.y = element_text(size = 6)) + 
  ylab('')
dev.off()

# EOF